<template>
  <div class="admin-management">
    <h2>管理员信息</h2>

    <!-- 添加管理员按钮 -->
    <div class="add-admin">
      <button @click="showAddModal = true" class="add-btn">+</button>
    </div>
    <!-- 管理员列表 -->
    <table>
      <thead>
      <tr>
        <th @click="sortAdmins('accountname')">
          账号名
          <span v-if="sortKey === 'accountname'" class="sort-arrow">
              <i :class="sortOrder === 'asc' ? 'arrow-up' : 'arrow-down'"></i>
            </span>
        </th>
        <th @click="sortAdmins('password')">
          密码
          <span v-if="sortKey === 'password'" class="sort-arrow">
              <i :class="sortOrder === 'asc' ? 'arrow-up' : 'arrow-down'"></i>
            </span>
        </th>
        <th @click="sortAdmins('realName')">
          真实姓名
          <span v-if="sortKey === 'realName'" class="sort-arrow">
              <i :class="sortOrder === 'asc' ? 'arrow-up' : 'arrow-down'"></i>
            </span>
        </th>
        <th @click="sortAdmins('idCard')">
          身份证号
          <span v-if="sortKey === 'idCard'" class="sort-arrow">
              <i :class="sortOrder === 'asc' ? 'arrow-up' : 'arrow-down'"></i>
            </span>
        </th>
        <th @click="sortAdmins('lastLoginTime')">
          最后登录时间
          <span v-if="sortKey === 'lastLoginTime'" class="sort-arrow">
              <i :class="sortOrder === 'asc' ? 'arrow-up' : 'arrow-down'"></i>
            </span>
        </th>
        <th>操作</th>
      </tr>
      </thead>
      <tbody>
      <tr v-for="admin in filteredAdmins" :key="admin.id">
        <td>{{ admin.accountname }}</td>
        <td>{{ admin.accountname === currentUser.accountname ? admin.passwd : admin.passwd.slice(0, 3) + '***' }}</td>
        <td>{{ admin.realName }}</td>
        <td>{{ admin.idCard.slice(0, 6) + '****' + admin.idCard.slice(-4) }}</td>
        <td>{{ admin.lasttime }}</td>
        <td>
          <button @click="editAdmin(admin)">修改</button>
          <button @click="confirmDelete(admin)">删除</button>
        </td>
      </tr>
      </tbody>
    </table>
    <!-- 添加管理员 Modal -->
    <div v-if="showAddModal" class="modal">
      <div class="modal-content">
        <h3>添加管理员</h3>
        <form @submit.prevent="addAdmin">
          <label>账号名：</label>
          <input v-model="newAdmin.accountname" required />
          <label>密码：</label>
          <input v-model="newAdmin.passwd" required />
          <label>真实姓名：</label>
          <input v-model="newAdmin.realName" required />
          <label>身份证号：</label>
          <input v-model="newAdmin.idCard" required />
          <label>密钥：</label>
          <input v-model="addKey" required />
          <button type="submit">添加</button>
          <button type="button" @click="showAddModal = false">取消</button>
        </form>
      </div>
    </div>
    <!-- 删除确认 Modal -->
    <div v-if="showDeleteModal" class="modal">
      <div class="modal-content">
        <h3>删除密钥</h3>
        <p>请输入密钥进行确认：</p>
        <input v-model="deleteKey" />
        <div class="deletebut">
          <button @click="deleteAdmin">确认删除</button>
          <button @click="showDeleteModal = false">取消</button>
        </div>
      </div>
    </div>
    <!-- 修改当前用户 Modal -->
    <div v-if="showEditModal" class="modal">
      <div class="modal-con">
        <h3>修改管理员信息</h3>
        <form @submit.prevent="updateAdmin">
          <label>账号名：</label>
          <input v-model="currentUser.accountname" required />
          <label>密码：</label>
          <input v-model="currentUser.passwd" required />
          <button type="submit">保存</button>
          <button type="button" @click="showEditModal = false">取消</button>
        </form>
      </div>
    </div>
    <!-- 提示信息 -->
    <div v-if="deletedAdminMessage" class="message">{{ deletedAdminMessage }}</div>
    <div v-if="filteredAdmins.length === 0">
      <p>目前没有符合条件的管理员信息。</p>
    </div>
  </div>
</template>

<script>
import { findAllAdmin, deleteAdmin, updateUser } from '../../api/admins';

export default {
  data() {
    return {
      admins: [],
      filteredAdmins: [],
      searchTerm: '',
      sortKey: '',
      sortOrder: 'asc',
      currentUser: { accountname: '', passwd: '' },
      showAddModal: false,
      showDeleteModal: false,
      deleteKey: '',
      addKey: '',
      newAdmin: { accountname: '', passwd: '', realName: '', idCard: '' },
      showEditModal: false,
      deletedAdminMessage: '',
      adminToDelete: null
    };
  },
  methods: {
    async search() {
      try {
        const response = await findAllAdmin();
        this.admins = response.data.data;
        this.filteredAdmins = [...this.admins];
        console.log('Admins fetched:', this.admins);
      } catch (error) {
        console.error('获取管理员数据失败：', error);
      }
    },
    filterAdmins() {
      this.filteredAdmins = this.admins.filter(admin => {
        return admin.accountname.includes(this.searchTerm);
      });
    },
    sortAdmins(key) {
      this.sortOrder = this.sortKey === key && this.sortOrder === 'asc' ? 'desc' : 'asc';
      this.sortKey = key;
      this.filteredAdmins.sort((a, b) => {
        if (key === 'lastLoginTime') {
          const dateA = new Date(a[key]);
          const dateB = new Date(b[key]);
          return this.sortOrder === 'asc' ? dateA - dateB : dateB - dateA;
        }
        if (this.sortOrder === 'asc') {
          return a[key] > b[key] ? 1 : -1;
        } else {
          return a[key] < b[key] ? 1 : -1;
        }
      });
    },
    editAdmin(admin) {
      this.currentUser = { ...admin }; // 将选中的管理员数据绑定到 currentUser
      this.showEditModal = true;
    },
    async updateAdmin() {
      try {
        // 调用更新管理员的 API
        await updateUser(this.currentUser);

        // 更新本地数据
        const index = this.admins.findIndex(admin => admin.id === this.currentUser.id);
        if (index !== -1) {
          this.admins[index] = { ...this.currentUser };
        }

        // 关闭模态框
        this.showEditModal = false;
        alert('管理员信息已更新！');
      } catch (error) {
        console.error('更新管理员信息失败：', error);
        alert('更新管理员信息失败，请稍后重试！');
      }
    },
    confirmDelete(admin) {
      this.showDeleteModal = true;
      this.adminToDelete = admin;
    },
    async deleteAdmin() {
      if (this.deleteKey === '123') {
        try {
          // 调用删除管理员的 API
          await deleteAdmin(this.adminToDelete.id);

          // 从本地列表中移除已删除的管理员
          this.admins = this.admins.filter(admin => admin.id !== this.adminToDelete.id);
          this.filteredAdmins = this.filteredAdmins.filter(admin => admin.id !== this.adminToDelete.id);

          // 关闭模态框并显示提示信息
          this.showDeleteModal = false;
          this.deletedAdminMessage = '管理员已删除！';
          setTimeout(() => {
            this.deletedAdminMessage = '';
          }, 2000);
        } catch (error) {
          console.error('删除管理员失败：', error);
          alert('删除管理员失败，请稍后重试！');
        }
      } else {
        alert('密钥错误，无法删除管理员！');
      }
    },
    addAdmin() {
      if (this.addKey !== '456') {
        alert('密钥错误，无法添加管理员！');
        return;
      }
      this.admins.push({ ...this.newAdmin, id: Date.now(), lastLoginTime: new Date().toLocaleString() });
      this.filteredAdmins = [...this.admins];
      this.showAddModal = false;
      this.newAdmin = { accountname: '', passwd: '', realName: '', idCard: '' };
      this.addKey = '';
    }
  },
  mounted() {
    this.search();
  }
};
</script>

  <style scoped>
  .admin-management {
    padding: 40px;
    font-family: 'Arial', sans-serif;
    background-color: #f7f7f7;
  }

  h2 {
    font-size: 24px;
    color: #333;
    text-align: center;
    margin-bottom: 20px;
  }

  .add-admin {
    position: fixed;
    bottom: 20px;
    right: 20px;
  }

  .add-btn {
    background-color: #007bff;
    color: white;
    border: none;
    border-radius: 50%;
    width: 50px;
    height: 50px;
    font-size: 30px;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    transition: background-color 0.3s ease;
  }

  .add-btn:hover {
    background-color: #0056b3;
  }

  button {
    background-color: #4CAF50;
    color: white;
    padding: 10px 20px;
    border: none;
    border-radius: 5px;
    cursor: pointer;
    transition: background-color 0.3s;
  }

  button:hover {
    background-color: #45a049;
  }
  .deletebut button {
    background-color: #4CAF50;
    color: white;
    border: none;
    border-radius: 5px;
    cursor: pointer;
    transition: background-color 0.3s;
    margin-top: 10px;
    margin-right: 10px;
    width: 100px;
  }

  .deletebut button:hover {
    background-color: #45a049;
  }
  .search {
    display: flex;
    justify-content: center;
    margin-bottom: 20px;
  }

  .search input {
    padding: 10px;
    width: 300px;
    font-size: 1rem;
    border: 1px solid #ddd;
    border-radius: 5px;
    transition: border-color 0.3s ease;
  }

  .search input:focus {
    border-color: #5b9bd5;
    outline: none;
  }

  table {
    width: 100%;
    border-collapse: collapse;
    margin-top: 20px;
    background-color: #fff;
    border-radius: 8px;
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  }

  th, td {
    padding: 12px;
    text-align: left;
    border-bottom: 1px solid #f2f2f2;
  }

  th {
    background-color: #f2f2f2;
    color: #333;
    cursor: pointer;
    position: relative;
  }

  th:hover {
    background-color: #e2e2e2;
  }

  th .sort-arrow {
    position: absolute;
    right: 10px;
  }

  .arrow-up::after {
    content: '↑';
  }

  .arrow-down::after {
    content: '↓';
  }

  tr:hover {
    background-color: #fafafa;
  }

  td button {
    background-color: #4CAF50;
    color: white;
    padding: 6px 12px;
    border-radius: 5px;
    border: none;
    cursor: pointer;
    transition: background-color 0.3s;
    margin-right: 10px;
  }

  td button:hover {
    background-color: #45a049;
  }

  td button:last-child {
    margin-right: 0;
  }

  .modal {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.5);
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .modal-content {
    background-color: white;
    padding: 20px;
    border-radius: 10px;
    width: 400px;
    box-shadow: 0px 4px 6px rgba(0, 0, 0, 0.1);
  }

  .modal-con {
    background-color: white;
    padding: 20px;
    border-radius: 10px;
    width: 400px;
    box-shadow: 0px 4px 6px rgba(0, 0, 0, 0.1);
  }

  h3 {
    font-size: 22px;
    color: #333;
    margin-bottom: 20px;
    text-align: center;
  }

  label {
    font-size: 14px;
    color: #555;
    margin-bottom: 5px;
    display: block;
  }

  button[type="submit"] {
    background-color: #2196F3;
    padding: 10px 20px;
    border: none;
    border-radius: 5px;
    color: white;
    cursor: pointer;
    font-size: 14px;
    transition: background-color 0.3s;
  }

  button[type="submit"]:hover {
    background-color: #1e88e5;
  }

  button[type="button"] {
    background-color: #f44336;
    padding: 10px 20px;
    border: none;
    border-radius: 5px;
    color: white;
    cursor: pointer;
    font-size: 14px;
    transition: background-color 0.3s;
  }

  button[type="button"]:hover {
    background-color: #e53935;
  }

  .modal-content input{
    text-align: center;
  }

  .modal-content form {
    display: flex;
    flex-direction: column;
  }

  .modal-content form button {
    margin-top: 15px;
  }

  .modal-con input{
    text-align: center;
  }

  .modal-con form {
    display: flex;
    flex-direction: column;
  }

  .modal-con form button {
    margin-top: 15px;
  }
  .message {
    color: green;
    font-size: 1rem;
    text-align: center;
    margin-top: 20px;
  }
  </style>